package com.example.robot;

import cn.hutool.json.JSONUtil;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class RobotMessageService {
    private static final Logger log = LoggerFactory.getLogger(RobotMessageService.class);

    /**
     * 企业微信群机器人推文本消息
     *
     * @param webhook
     * @param text    {
     *                "msgtype": "text",
     *                "text": {
     *                "content": "广州今日天气：29度，大部分多云，降雨概率：60%",
     *                "mentioned_list":["wangqing","@all"],
     *                "mentioned_mobile_list":["13800001111","@all"]
     *                }
     *                }
     * @return
     */
    public boolean sendGroupMessage(String webhook, Map<String, Object> text) {
        HttpPost httpPost = new HttpPost(webhook);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        Map<String, Object> postBody = new HashMap<>(2);
        postBody.put("msgtype", "text");
        postBody.put("text", text);
        httpPost.setEntity(new StringEntity(JSONUtil.toJsonStr(postBody), "UTF-8"));

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);

        RobotMessageResponse response;
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
             CloseableHttpResponse responseEntity = httpClient.execute(httpPost)) {
            response = JSONUtil.toBean(EntityUtils.toString(responseEntity.getEntity()), RobotMessageResponse.class);
            if (response.getErrcode() == 0) {
                return true;
            } else {
                log.error("sendGroupMessage error, response={}", JSONUtil.toJsonStr(requestConfig));
                return false;
            }
        } catch (IOException e) {
            log.error("getAcsResponse error", e);
        }
        return false;
    }

    private static class RobotMessageResponse {
        private Integer errcode;
        private String errmsg;

        public Integer getErrcode() {
            return errcode;
        }

        public void setErrcode(Integer errcode) {
            this.errcode = errcode;
        }

        public String getErrmsg() {
            return errmsg;
        }

        public void setErrmsg(String errmsg) {
            this.errmsg = errmsg;
        }
    }
}
